<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="60px">
      <el-form-item label="校区" prop="schoolId">
        <treeselect v-model="queryParams.schoolId" :options="deptOptions" :normalizer="normalizer" placeholder="选择所属校区" style="width:200px"/>
      </el-form-item>
      <el-form-item label="班级" prop="classesId">
        <el-select filterable v-model="queryParams.classesId" placeholder="请选择所属班级" clearable size="small" style="width:200px">
          <el-option v-for="dict in classesList" :key="dict.id" :label="dict.classesName" :value="dict.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学生" prop="studentId">
        <el-select filterable v-model="queryParams.studentId" placeholder="请选择学生" clearable size="small" style="width:200px">
          <el-option v-for="dict in studentXYList" :key="dict.userId" :label="dict.userName+':'+dict.phonenumber" :value="dict.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="老师" prop="teacherId">
        <el-select filterable v-model="queryParams.teacherId" placeholder="请选择操作老师" clearable size="small" style="width:200px">
          <el-option v-for="dict in teacherList" :key="dict.userId" :label="dict.userName+':'+dict.phonenumber" :value="dict.userId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="耗课">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:consume:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:consume:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:consume:remove']"
        >删除</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:consume:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="consumeList" @selection-change="handleSelectionChange" @sort-change="sortChange">
      <!--<el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="所属校区" align="left" prop="schoolId" :formatter="getSchool"/>
      <el-table-column label="所属班级" align="left" prop="classesId" :formatter="getClasses"/>
      <el-table-column label="学生" align="left" prop="studentId" width="300" :formatter="getStudentXY"/>
      <el-table-column label="耗课金额" align="right" prop="consumeAmount" sortable="custom"/>
      <el-table-column label="操作老师" align="left" prop="teacherId" width="300" :formatter="getTeacher"/>
      <el-table-column label="耗课时间" align="center" prop="createTime" width="160" sortable="custom">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:consume:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:consume:remove']"
          >删除</el-button>
        </template>
      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改耗课信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属校区" prop="schoolId">
          <treeselect v-model="form.schoolId" :options="deptOptions" :normalizer="normalizer" placeholder="选择所属校区" />
        </el-form-item>
        <el-form-item label="所属班级" prop="classesId">
          <el-select filterable v-model="form.classesId" placeholder="请选择所属班级" clearable size="small">
            <el-option v-for="dict in classesList" :key="dict.id" :label="dict.classesName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生" prop="studentId">
          <el-select filterable v-model="form.studentId" placeholder="请选择学生" clearable size="small">
            <el-option v-for="dict in studentXYList" :key="dict.userId" :label="dict.userName+':'+dict.phonenumber" :value="dict.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="耗课金额" prop="consumeAmount">
          <el-input v-model="form.consumeAmount" placeholder="请输入耗课金额" />
        </el-form-item>
        <el-form-item label="操作老师" prop="teacherId">
          <el-select filterable v-model="form.teacherId" placeholder="请选择操作老师" clearable size="small">
            <el-option v-for="dict in teacherList" :key="dict.userId" :label="dict.userName+':'+dict.phonenumber" :value="dict.userId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConsume, getConsume, delConsume, addConsume, updateConsume, exportConsume } from "@/api/business/consume";
import { listDept } from "@/api/system/dept";
import { listClasses } from "@/api/business/classes";
import { listStudentXY, listOpt } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Consume",
  components: {
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 耗课信息表格数据
      consumeList: [],
      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      // 是否显示弹出层
      open: false,
      deptOptions: [],//学校树选项
      schoolList: [],//学校列表
      classesList: [],//班级列表
      studentXYList: [],//学生列表
      teacherList: [],//老师列表
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schoolId: null,
        classesId: null,
        studentId: null,
        consumeAmount: null,
        teacherId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        consumeAmount: [
          { required: true, message: "耗课金额不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    listDept().then(response => {
        this.schoolList = response.data;
	      this.deptOptions = this.handleTree(response.data, "deptId");
    });
    listClasses().then(response => {
        this.classesList = response.rows;
    });
    listStudentXY().then(response => {
        this.studentXYList = response.rows;
    });
    listOpt().then(response => {
        this.teacherList = response.rows;
    });
  },
  watch: {
    'queryParams.schoolId': 'currSchoolChangeQ',
    'form.schoolId': 'currSchoolChange'
  },
  methods: {
    currSchoolChangeQ(val) {
      let params = {schoolId: val};
      listClasses(params).then(response => {
        this.classesList = response.rows;
      });
    },
    currSchoolChange(val) {
      let params = {schoolId: val};
      listClasses(params).then(response => {
        this.classesList = response.rows;
      });
    },
    /** 转换学校数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    getSchool(row) {
      for (let i in this.schoolList) {
        if (this.schoolList[i].deptId === row.schoolId) {
          return this.schoolList[i].deptName;
        }
      }
    },
    getClasses(row) {
      for (let i in this.classesList) {
        if (this.classesList[i].id === row.classesId) {
          return this.classesList[i].classesName;
        }
      }
    },
    getStudentXY(row) {
      for (let i in this.studentXYList) {
        if (this.studentXYList[i].userId === row.studentId) {
          return this.studentXYList[i].userName+':'+this.studentXYList[i].phonenumber;
        }
      }
    },
    getTeacher(row) {
      for (let i in this.teacherList) {
        if (this.teacherList[i].userId === row.teacherId) {
          return this.teacherList[i].userName+':'+this.teacherList[i].phonenumber;
        }
      }
    },
    sortChange(column) {
      this.loading = true;
      if (column.prop === 'consumeAmount') {
        this.queryParams.order = 'consume_amount';
      } else if (column.prop === 'createTime') {
        this.queryParams.order = 'create_time';
      }
      if (column.order === 'ascending') {
        this.queryParams.orderType = 'asc';
      } else if (column.order === 'descending') {
        this.queryParams.orderType = 'desc';
      }      
      listConsume(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.consumeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询耗课信息列表 */
    getList() {
      this.loading = true;
      listConsume(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.consumeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        schoolId: null,
        classesId: null,
        studentId: null,
        consumeAmount: null,
        teacherId: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加耗课信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getConsume(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改耗课信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConsume(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConsume(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除耗课信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delConsume(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有耗课信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportConsume(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
